package com.example.rocketmq.timewheel.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.example.rocketmq.timewheel.mq.RocketMQConfig;
import com.example.rocketmq.timewheel.model.ScheduledTask;

import io.netty.util.HashedWheelTimer;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

/**
 * 任务生产者服务
 */
@Service
@Slf4j
public class TaskProducerService {
    
    @Resource
    private HashedWheelTimer hashedWheelTimer;
    
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    
    /**
     * 添加定时任务到时间轮
     */
    public void addTaskToTimeWheel(ScheduledTask task) {
        log.info("添加定时任务到时间轮: {}", JSON.toJSONString(task));
        
        // 将任务添加到时间轮
        hashedWheelTimer.newTimeout(new TimerTask() {
            @Override
            public void run(Timeout timeout) throws Exception {
                log.info("时间轮触发任务，发送到RocketMQ: {}", task.getTaskId());
                // 任务到期，发送到RocketMQ
                sendTaskToMQ(task);
            }
        }, task.getDelay(), java.util.concurrent.TimeUnit.MILLISECONDS);
    }
    
    /**
     * 发送任务到RocketMQ
     */
    private void sendTaskToMQ(ScheduledTask task) {
        try {
            rocketMQTemplate.convertAndSend(RocketMQConfig.SCHEDULED_TASK_TOPIC, task);
            log.info("任务发送到RocketMQ成功: {}", task.getTaskId());
        } catch (Exception e) {
            log.error("任务发送到RocketMQ失败: {}", task.getTaskId(), e);
            // 可以在这里添加重试机制
        }
    }
}
